package snuvm.venus;

import snuvm.*;
import javax.swing.*;
import java.io.*;
 
/*
Copyright (c) 2009-2010,  Jeongho Nah, Gangwon Jo, Jaejin Lee

Developed by 
	Jeongho Nah (jeongho"at"aces.snu.ac.kr)
	Gangwon Jo (gangwon"at"aces.snu.ac.kr)
	Jaejin Lee (jlee"at"cse.snu.ac.kr)


Permission is hereby granted to use this version of the code 
under the same terms as MARS, which has the following license:

--
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson (psanderson"at"otterbein.edu)
and Kenneth Vollmar (kenvollmar"at"missouristate.edu)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
 /**
  * Manage the file being edited.
  * Currently only manages one file at a time, but can be expanded. 
  */
 
    public class Editor {
   
      private VenusUI mainUI;
      private String mainUIbaseTitle;
    /* number of times File->New has been selected.  Used to generate
     * default filename until first Save or Save As.
     */
      private int newUsageCount; 
    
    /**
     * Create editor.
     *
     * @param ui the GUI that owns this editor
     */
       public Editor(VenusUI ui) {
         mainUI = ui;
         FileStatus.reset(); 
         mainUIbaseTitle = mainUI.getTitle();
         newUsageCount = 0;
      }
   
      /**
   	 * Generates a default file name
   	 *
   	 * @return returns string mipsN.asm, where N is 1,2,3,...
   	 */
       public String getNextDefaultFilename() {
         newUsageCount++;
         return "snuvm"+newUsageCount+".asm";
      }
    
   
      /** Places name of file currently being edited into the title bar
   	 * of the editing window.  If the contents of the editing window
   	 * have been modified since the New, Open, Save or SaveAs operation,
   	 * the client is responsible for calling this method to display
   	 * an asterisk (*) next to the file name in the title bar. And
   	 * responsible for calling it again after Save or SaveAs to repaint
   	 * the filename without the asterisk.
   	 */
       public void setFrameTitle() {
         if (FileStatus.getName() != "") {
            mainUI.setTitle(FileStatus.getName() + 
                        ((FileStatus.isEdited())? "*" : " ") + 
               			" - "  + mainUIbaseTitle);
         } 
         else {
            mainUI.setTitle(mainUIbaseTitle);
         }
      }
   	
   	/**
   	 * Pops up a dialog box to do "Save" operation. 
   	 * @return true if the file was actually saved.
   	 */
       public boolean save() {
         return saveSaveAs(false, "Save");
      }
   	
   	/**
   	 * Pops up a dialog box to do "Save As" operation.  If necessary
   	 * an additional overwrite dialog is performed.
   	 * @return true if the file was actually saved.
   	 */
       public boolean saveAs() {
         return saveSaveAs(true, "Save As");
      }
   	
   	/* This dual purpose helper method will perform either Save or SaveAs.
   	 * If the first argument is true, it does SaveAs.   The second
   	 * argument is the title to place in the dialog's title bar.
   	 */
       private boolean saveSaveAs(boolean saveAs, String title) {
         EditPane editPane = mainUI.getMainPane().getEditPane();
         File theFile = FileStatus.getFile();
         if (saveAs || theFile==null) {
            JFileChooser saveDialog = null;
            boolean operationOK = false;
            while (!operationOK) {
               saveDialog = new JFileChooser(editPane.getCurrentDirectoryPath());
               saveDialog.setDialogTitle(title);
               int decision = saveDialog.showSaveDialog(mainUI);
               if (decision != JFileChooser.APPROVE_OPTION) {
                  return false;
               }
               theFile = saveDialog.getSelectedFile();
               operationOK = true;
               if (saveAs && theFile.exists()) {
                  int overwrite = JOptionPane.showConfirmDialog(mainUI,
                     "File "+theFile.getName()+" already exists.  Do you wish to overwrite it?",
                     "Overwrite existing file?",
                     JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                  switch (overwrite) {
                     case JOptionPane.YES_OPTION :
                        operationOK = true;
                        break;
                     case JOptionPane.NO_OPTION :
                        operationOK = false;
                        break;
                     case JOptionPane.CANCEL_OPTION :
                        return false;
                     default : // should never occur
                        return false;
                  }
               }
            }
            FileStatus.setFile(theFile);
            FileStatus.setName(theFile.getPath());
            editPane.setCurrentDirectoryPath(saveDialog.getCurrentDirectory().getPath());
         }
         try {
            BufferedWriter outFileStream = new BufferedWriter(new FileWriter(theFile));          
            outFileStream.write(editPane.getSource(), 0, editPane.getSource().length());
            outFileStream.close();
         } 
             catch(java.io.IOException c) {
               JOptionPane.showMessageDialog(null,title+" operation could not be completed due to an error:\n"+c,
					title+" Operation Failed", JOptionPane.ERROR_MESSAGE);
               return false;
            }
         FileStatus.setSaved(true);
         FileStatus.setEdited(false);
         mainUI.editor.setFrameTitle();
         FileStatus.set(FileStatus.NOT_EDITED);
         return true;
      }
   
   
   /**
    * Called by several of the Action objects when there is potential
    * loss of editing changes.  Specifically: if there is a current
    * file open for editing and its modify flag is true, then give user
    * a dialog box with choice to save, discard edits, or cancel and
    * carry out the decision.  This applies to File->New, File->Open,
    * File->Close, and File->Exit.
    *
    * @return false means user selected Cancel so caller should do that.
    * Return of true means caller can proceed (edits were saved or discarded).
    */
       public boolean editsSavedOrAbandoned() {
         if (!FileStatus.isEdited()) {
            return true;
         }
         int decision = JOptionPane.showConfirmDialog(mainUI,
            "Program changes will be lost unless you save.  Do you wish to save now?",
            "Save program changes?",
            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
         switch (decision) {
            case JOptionPane.YES_OPTION :
               return this.saveSaveAs(false, "Save");
            case JOptionPane.NO_OPTION :
               return true;
            case JOptionPane.CANCEL_OPTION :
               return false;
            default : // should never occur
               return false;
         }
      }
   }